package com.beerandjesus.sportofkings.handicapper.dao;

import com.beerandjesus.sportofkings.handicapper.model.TurfSire;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * Date: Jun 8, 2012
 * Time: 12:41:51 PM
 */
public class DatabaseImpl implements Database {
    private TurfSireDAO turfSireDAO;
    private ConnectionManager connectionManager;
    private boolean initialized = false;

    public DatabaseImpl() {}

    public DatabaseImpl(TurfSireDAO turfSireDAO, ConnectionManager connectionManager) {
        this.turfSireDAO = turfSireDAO;
        this.connectionManager = connectionManager;
    }

    public TurfSire getTurfSireByName(String name) {
        Connection conn = getConnectionManager().getTurfSireDatabaseConnection();
        TurfSire byName = null;
        try {
            byName = getTurfSireDAO().getTurfSireByName(name, conn);
        } catch (DAOException e) {
            throw new DatabaseException("Error getting turf sire " + name);
        } finally {
            getConnectionManager().releaseConnection(conn);
        }
        return byName;
    }

    public synchronized void init() {
        if (initialized) {
            throw new DatabaseException("Database already initialized");
        }
        System.out.println("INFO: " + this.getClass().getCanonicalName() + ": init()");
        Connection conn = getConnectionManager().getTurfSireDatabaseConnection();
        try {
            System.out.println("INFO: " + this.getClass().getCanonicalName() + ": connecting to " + conn.getMetaData().getURL());
        } catch (SQLException e) {
            throw new DatabaseException("Error getting database metadata", e);
        }
        int count;
        try {
            getTurfSireDAO().buildDatabase(conn);
            count = getTurfSireDAO().getRowCount(conn);
        } catch (DAOException e) {
            throw new DatabaseException("Error building turf sire database", e);
        } finally {
            getConnectionManager().releaseConnection(conn);
        }
        System.out.println("INFO: " + this.getClass().getCanonicalName() + ": Database initialized, row count: " + count);
        initialized = true;
    }

    public void setTurfSireDAO(TurfSireDAO dao) {
        this.turfSireDAO = dao;
    }

    public TurfSireDAO getTurfSireDAO() {
        return turfSireDAO;
    }

    public void setConnectionManager(ConnectionManager manager) {
        this.connectionManager = manager;
    }

    public ConnectionManager getConnectionManager() {
        return connectionManager;
    }
}
